require 'digest/sha1'

class UserController < ApplicationController
 
  before_filter :authorize, :only => [:logout, :index]

  def register
    if request.post? and params[:user]
      @user = User.new(params[:user])
      if @user.save
         flash[:notice] = "User #{@user.first_name} #{@user.family_name}  created!"
         session[:user_id] = @user.id 
         redirect_to :action => "index"
      end
    end
  end
    
  # Rewrite after analisys
  def login
    session[:user_id] = nil
    if request.get?
      @user = User.new(:remember_me => cookies[:remember_me] || "0")
    elsif request.post? and params[:user] 
      @user = User.new(params[:user])
      authenticated_user = User.authenticate(@user.email, @user.password)
      if authenticated_user
        authenticated_user.copy_transient_fields(@user)  
        @user = authenticated_user
        @user.login!(session)
        if @user.remember_me == "1"
          @user.remember!(cookies)
        else
          @user.forget!(cookies)   
        end
        redirect_to_original_uri   
      else
        flash[:notice] = "Invalid email/password combination"
        @user.password = nil
      end
    end
  end

  def logout
    @user.logout!(session, cookies)
    flash[:notice] = "Logged out."
    redirect_to :action => "index", :controller => "site"
  end

  def index
    @user = User.find(session[:user_id])

    render :text => "Welcome to user profile!"
  end

  private

  def redirect_to_original_uri
    uri = session[:original_uri]
    session[:original_uri] = nil
    redirect_to(uri || { :action => "index" }) 
  end

end

